<template>
  <div class="order-manage">
    <el-card>
      <template #header>
        <div class="card-header">
          <span class="title">订单管理</span>
          <div class="header-actions">
            <el-select
              v-model="statusFilter"
              placeholder="筛选状态"
              clearable
              style="width: 150px; margin-right: 10px"
              @change="handleSearch">
              <el-option label="待支付" :value="0" />
              <el-option label="配送中" :value="1" />
              <el-option label="已完成" :value="2" />
              <el-option label="已取消" :value="3" />
            </el-select>
            <el-input
              v-model="searchKeyword"
              placeholder="搜索订单号或用户名"
              style="width: 250px"
              clearable
              @clear="handleSearch"
              @keyup.enter="handleSearch">
              <template #append>
                <el-button :icon="Search" @click="handleSearch" />
              </template>
            </el-input>
          </div>
        </div>
      </template>

      <!-- 订单列表表格 -->
      <el-table :data="orderList" v-loading="loading" stripe>
        <el-table-column prop="id" label="订单号" width="180" />
        <el-table-column prop="user_name" label="用户" width="120" />
        <el-table-column prop="store_name" label="商家" width="150" />
        <el-table-column prop="takeout_name" label="外卖" width="150" />
        <el-table-column prop="num" label="数量" width="80" />
        <el-table-column prop="price" label="总价" width="100">
          <template #default="{ row }">
            <span style="color: #f56c6c; font-weight: bold">¥{{ row.price.toFixed(2) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="state" label="状态" width="100">
          <template #default="{ row }">
            <el-tag v-if="row.state === 0" type="warning">待支付</el-tag>
            <el-tag v-else-if="row.state === 1" type="primary">配送中</el-tag>
            <el-tag v-else-if="row.state === 2" type="success">已完成</el-tag>
            <el-tag v-else type="info">已取消</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="create_time" label="下单时间" width="180" />
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="{ row }">
            <el-button type="info" size="small" @click="viewDetails(row)">
              详情
            </el-button>
            <el-button type="warning" size="small" @click="handleChangeState(row)">
              改状态
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[10, 20, 50]"
        layout="total, sizes, prev, pager, next"
        @size-change="fetchOrders"
        @current-change="fetchOrders"
        style="margin-top: 20px; justify-content: center"
      />
    </el-card>

    <!-- 订单详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="订单详情" width="600px">
      <el-descriptions :column="2" border v-if="currentOrder">
        <el-descriptions-item label="订单号">{{ currentOrder.id }}</el-descriptions-item>
        <el-descriptions-item label="用户">{{ currentOrder.user_name }}</el-descriptions-item>
        <el-descriptions-item label="商家">{{ currentOrder.store_name }}</el-descriptions-item>
        <el-descriptions-item label="外卖">{{ currentOrder.takeout_name }}</el-descriptions-item>
        <el-descriptions-item label="数量">{{ currentOrder.num }}</el-descriptions-item>
        <el-descriptions-item label="总价">
          <span style="color: #f56c6c; font-weight: bold">¥{{ currentOrder.price.toFixed(2) }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="配送地址" :span="2">{{ currentOrder.address }}</el-descriptions-item>
        <el-descriptions-item label="联系电话">{{ currentOrder.phone }}</el-descriptions-item>
        <el-descriptions-item label="订单状态">
          <el-tag v-if="currentOrder.state === 0" type="warning">待支付</el-tag>
          <el-tag v-else-if="currentOrder.state === 1" type="primary">配送中</el-tag>
          <el-tag v-else-if="currentOrder.state === 2" type="success">已完成</el-tag>
          <el-tag v-else type="info">已取消</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="下单时间" :span="2">{{ currentOrder.create_time }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 修改订单状态对话框 -->
    <el-dialog v-model="stateDialogVisible" title="修改订单状态" width="500px">
      <el-form :model="stateForm" label-width="100px">
        <el-form-item label="订单号">
          <span>{{ stateForm.orderId }}</span>
        </el-form-item>
        <el-form-item label="当前状态">
          <el-tag v-if="stateForm.currentState === 0" type="warning">待支付</el-tag>
          <el-tag v-else-if="stateForm.currentState === 1" type="primary">配送中</el-tag>
          <el-tag v-else-if="stateForm.currentState === 2" type="success">已完成</el-tag>
          <el-tag v-else type="info">已取消</el-tag>
        </el-form-item>
        <el-form-item label="新状态">
          <el-select v-model="stateForm.newState" placeholder="请选择状态" style="width: 100%">
            <el-option label="待支付" :value="0" />
            <el-option label="配送中" :value="1" />
            <el-option label="已完成" :value="2" />
            <el-option label="已取消" :value="3" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="stateDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmChangeState">确认修改</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import { adminApis } from '@/assets/apis/AdminApis'

const loading = ref(false)
const orderList = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const searchKeyword = ref('')
const statusFilter = ref('')

const detailDialogVisible = ref(false)
const currentOrder = ref(null)

// 修改状态
const stateDialogVisible = ref(false)
const stateForm = ref({
  orderId: '',
  currentState: 0,
  newState: 0
})

const fetchOrders = async () => {
  loading.value = true
  try {
    const data = await adminApis.getOrders(
      currentPage.value,
      pageSize.value,
      searchKeyword.value,
      statusFilter.value
    )
    orderList.value = data.orders
    total.value = data.total
  } catch (error: any) {
    console.error('获取订单列表失败：', error)
    ElMessage.error(error.error || '获取订单列表失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  currentPage.value = 1
  fetchOrders()
}

const viewDetails = (row: any) => {
  currentOrder.value = row
  detailDialogVisible.value = true
}

// 打开修改状态对话框
const handleChangeState = (row: any) => {
  stateForm.value = {
    orderId: row.id,
    currentState: row.state,
    newState: row.state
  }
  stateDialogVisible.value = true
}

// 确认修改状态
const confirmChangeState = async () => {
  if (stateForm.value.newState === stateForm.value.currentState) {
    ElMessage.warning('请选择不同的状态')
    return
  }

  try {
    await adminApis.updateOrderState(
      stateForm.value.orderId,
      stateForm.value.newState
    )
    ElMessage.success('订单状态更新成功')
    stateDialogVisible.value = false
    fetchOrders()
  } catch (error: any) {
    console.error('更新订单状态失败：', error)
    ElMessage.error(error.error || '更新失败')
  }
}

// 删除订单
const handleDelete = (row: any) => {
  ElMessageBox.confirm(
    `确定删除订单"${row.id}"吗？删除后将无法恢复！`,
    '警告',
    {
      confirmButtonText: '确定删除',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await adminApis.deleteOrder(row.id)
      ElMessage.success('订单删除成功')
      fetchOrders()
    } catch (error: any) {
      console.error('删除订单失败：', error)
      ElMessage.error(error.error || '删除失败')
    }
  }).catch(() => {
    // 用户取消删除
  })
}

onMounted(() => {
  fetchOrders()
})
</script>

<style scoped>
.order-manage {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  align-items: center;
}

.title {
  font-size: 18px;
  font-weight: bold;
}
</style>
